package com.tl.khadmin.service.impl;

import java.beans.PropertyEditorSupport;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.tl.khadmin.HaolibeiApi;
import com.tl.khadmin.bean.*;
import com.tl.khadmin.mapper.FreightMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.tl.khadmin.bean.dto.ProductSupplyDetailDto;
import com.tl.khadmin.bean.dto.ProductSupplyDto;
import com.tl.khadmin.bean.dto.ProductSupplyListDto;
import com.tl.khadmin.controller.NewsController;
import com.tl.khadmin.mapper.ProductImgMapper;
import com.tl.khadmin.mapper.ProductSupplyMapper;
import com.tl.khadmin.mapper.ProductSupplySpecificationMapper;
import com.tl.khadmin.page.Page;
import com.tl.khadmin.service.ProductSupplyIService;
import com.tl.khadmin.util.CommonUtil;
import com.tl.khadmin.util.Constant;
import com.tl.khadmin.util.PutParamUtil;

@Service
public class ProductSupplyServiceImpl implements ProductSupplyIService {

    private static Logger log = Logger.getLogger(ProductSupplyServiceImpl.class);
    @Resource
    private ProductSupplyMapper productSupplyMapper;
    @Resource
    private ProductSupplySpecificationMapper productSupplySpecificationMapper;
    @Resource
    private ProductImgMapper productImgMapper;
    @Resource
    private FreightMapper freightMapper;


    @Override
    public String audit(HttpSession session, ProductSupplyDto productSupplyDto) {
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        //非内部供应商账号不能审核
        if (supplier.getIsInterior() == 0) {
            return CommonUtil.returnMapResultToJson("fail", "账号无权限");
        }
        ProductSupply ore = new ProductSupply();
        Staff staff = (Staff) session.getAttribute(Constant.USER);
        ore.setAuditStatus(productSupplyDto.getAuditStatus());
        ore.setId(productSupplyDto.getId());
        ore.setAuditId(staff.getId());
        ore.setAuditTime(new Date());
        int result = productSupplyMapper.updateByPrimaryKeySelective(ore);
        if (result == 1) {
            for (ProductSupplySpecification sf : productSupplyDto.getSpecificationList()) {
                ProductSupplySpecification temp = new ProductSupplySpecification();
                temp.setId(sf.getId());
                temp.setUnitPriceAudit(sf.getUnitPriceAudit());
                productSupplySpecificationMapper.updateByPrimaryKeySelective(temp);
            }
        }
		updateHaolibeiProduct(productSupplyDto,true);
		return CommonUtil.returnMapResultByRows(result, "提交成功", "提交失败，请重试");
    }


    private void updateHaolibeiProduct(ProductSupplyDto productSupplyDto,boolean marketable ) {
		if(productSupplyDto.getAuditStatus()!=2){
			return;
		}
        List<PorductSupHaolibeiDao> infos = productSupplyMapper.getSupUploadInfo(productSupplyDto.getId());
        PorductSupHaolibeiDao minNumberInfos = infos.stream().min(Comparator.comparing(PorductSupHaolibeiDao::getUnitNumber)).get();
        Map<String, String> params = new HashMap<>();
        params.put("barcode", infos.get(0).getBarCode());
        params.put("validdate", infos.get(0).getValidDate());
        params.put("stockqty", String.valueOf(infos.get(0).getQty()));
        params.put("price", String.valueOf(minNumberInfos.getAuditPrice()));
        params.put("bn",infos.get(0).getBn());
        params.put("marketable",marketable?"true":"false");
        if(infos.get(0).getFreightId()>0){
            Freight freight = freightMapper.selectByPrimaryKey(productSupplyDto.getFreightId());
            if(freight!=null) {
                params.put("freight", String.format("%s_gyl_%s", freight.getFreightName(), freight.getSupplierId()));
            }
        }
        List<Integer> stand = new ArrayList<>(infos.size());
        List<Double> standPrice = new ArrayList<>(infos.size());
        for (PorductSupHaolibeiDao item : infos
        ) {
            if (item.getUnitNumber() > 0) {
                stand.add(item.getUnitNumber());
                if (item.getAuditPrice() > 0) {
                    standPrice.add(item.getAuditPrice());
                } else {
                    standPrice.add(item.getUnitPrice());
                }
            }
        }
        if (stand.size() > 0) {
            params.put("stand", StringUtils.join(stand.toArray(), "_"));
            params.put("standprice", StringUtils.join(standPrice.toArray(), "_"));
        }
        try{
			String result =  HaolibeiApi.PostHaoliBeiProduct(params);
			log.info(String.format("%s%s","haolibei商品提交",result));

		}
        catch (Exception ex){
			log.info(String.format("%s%s","添加失败",ex.getMessage()));

		}

    }


    @Override
    public Map<String, Object> queryProductById(Long id) {
        Map<String, Object> ret = new HashMap<>();
        ProductSupplyDetailDto productSupplyDetailDto = productSupplyMapper.queryProductSupplyDetailById(id);
        ret.put("productSupply", productSupplyDetailDto);
        ret.put("imgList", productImgMapper.queryByProductId(productSupplyDetailDto.getProductId(), 1));
        ret.put("specificatioList", productSupplySpecificationMapper.findByProductSupplyId(id));
        return ret;
    }

    @Override
    public Map<String, String> upLoadDeclarationImg(String basePath, MultipartFile file) {
        Map<String, String> ret = new HashMap<String, String>();
        if (file == null) {
            ret.put("result", "fail");
            return ret;
        }
        try {
            DateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
            File imgDir = new File(basePath);
            if (!imgDir.exists()) {
                imgDir.mkdirs();
            }
            String datePath = df.format(new Date());
            String picurl = datePath + ".jpg";
            File toFile = new File(basePath, picurl);
            file.transferTo(toFile);
            ret.put("result", "success");
            ret.put("message", "/upload/productimg/" + picurl);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            ret.put("reulst", "fail");
            return ret;
        }
    }

    @Override
    public Page<ProductSupplyListDto> showProductSupplyByPage(HttpSession session,
                                                              Integer pageNum, Integer pageSize, Map<String, Object> params) {
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        PutParamUtil.setParamIsInterior(supplier, params);    //设置查询供应商数据范围
        Page<ProductSupplyListDto> page = new Page<ProductSupplyListDto>(pageNum, pageSize);
        params.put("page", page);
        List<ProductSupplyListDto> list = productSupplyMapper.showProductSupplyByPage(params);
        page.setResult(list);
        return page;
    }

    @Override
    public Map<String, Object> saveProductSupply(ProductSupply productSupply) {
        Map<String, Object> map = new HashMap<String, Object>();
        productSupply.setCreateTime(new Date());
        Integer result = productSupplyMapper.insertSelective(productSupply);
//		Integer id = productSupply.getId();
        if (1 == result) {
            map.put("result", "success");
//			map.put("message", id);
            return map;
        } else {
            map.put("result", "fail");
            return map;
        }
    }

    @Override
    public int updateSaleState(Long id, Integer saleStatus) {
        ProductSupply productSupply = new ProductSupply();
        productSupply.setId(id);
        productSupply.setSaleStatus(saleStatus);
        return productSupplyMapper.updateByPrimaryKeySelective(productSupply);
    }

    @Override
    public String saveProductSupply(HttpSession session, ProductSupplyDto productSupplyDto) {
        Staff staff = (Staff) session.getAttribute(Constant.USER);
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        productSupplyDto.setCreateId(staff.getId());
        productSupplyDto.setCreateTime(new Date());
        productSupplyDto.setSupplierId(supplier.getId());
        int result = productSupplyMapper.insertproductSupplyDto(productSupplyDto);
        if (result == 1) {
            List<ProductSupplySpecification> list = productSupplyDto.getSpecificationList();
            int suc = 1;
            for (ProductSupplySpecification psf : list) {
                if (psf.getNumber() != null && psf.getUnitPrice() != null) {
                    psf.setProductSupplyId(productSupplyDto.getId());
                    int row = productSupplySpecificationMapper.insertSelective(psf);
                    if (row != 1) {
                        suc = 0;
                    }
                }
            }
            if (suc == 0) {
                log.info("插入供货规格失败");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
                return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
            }

        }
        return CommonUtil.returnMapResultByRows(result, "提交成功", "提交失败，请重试");
    }

    @Override
    public String updateProductSupply(HttpSession session, ProductSupplyDto productSupplyDto) {

        List<ProductSupplySpecification> specificationList = productSupplyDto.getSpecificationList();
        if (specificationList == null || specificationList.size() == 0) {
            return CommonUtil.returnMapResultToJson("fail", "规格报价不能为空");
        }

        //修改规格
        productSupplySpecificationMapper.deleteBySupplyId(productSupplyDto.getId());
        int suc = 1;
        for (ProductSupplySpecification psf : specificationList) {
            if (psf.getNumber() != null && psf.getUnitPrice() != null) {
                psf.setProductSupplyId(productSupplyDto.getId());
                int row = productSupplySpecificationMapper.insertSelective(psf);
                if (row != 1) {
                    suc = 0;
                }
            }
        }
        if (suc == 0) {
            log.info("修改供货规格失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            return CommonUtil.returnMapResultToJson("fail", "提交失败");
        }

        //修改供货信息
        int rowUpdate = productSupplyMapper.updateProductSupplyDto(productSupplyDto);
        if (rowUpdate != 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            return CommonUtil.returnMapResultToJson("fail", "提交失败");
        }

        return CommonUtil.returnMapResultToJson("success", "提交成功");
    }


}
